﻿using K9Nano.Updater.Utils;

namespace K9Nano.Updater.Pipes;

public class RollbackPipe : UpdatePipeBase
{
    public RollbackPipe()
    {
        PipeName = "回滚";
    }

    protected override bool CanInvoke(UpdateContext context)
    {
        return context.Backuped && !context.Success;
    }

    protected override Task InvokeCoreAsync(UpdateContext context, CancellationToken cancellation)
    {
        context.LogWarning("更新失败，开始回滚到版本：{0}", context.CurrentVersion);
        var backupPath = context.GetBackupDirectory();
        if (!Directory.Exists(backupPath))
        {
            context.LogError("备份目录不存在，无法回滚");
            return Task.CompletedTask;
        }

        PathUtils.MoveDirectory(backupPath, context.WorkingDirectory);
        context.LogInformation("成功回滚到版本：{0}", context.CurrentVersion);
        return Task.CompletedTask;
    }
}